package com.azt.data.action;

import com.azt.api.dto.*;
import com.azt.api.model.AjaxJson;
import com.azt.api.model.Pagination;
import com.azt.api.pojo.Admin;
import com.azt.api.pojo.DataFunction;
import com.azt.api.service.AdminService;
import com.azt.api.service.PaginationService;
import com.azt.data.utils.ContextUtils;
import com.azt.data.utils.ExcelExportEntityUtil;
import com.azt.data.utils.Globals;
import com.azt.provider.mapper.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xiaoleilu.hutool.util.CollectionUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by zouheyuan on 2017/4/12.
 */
@Controller
public class IndexAction extends BaseAction{

    @Autowired
    private AdminService adminService;

    @Autowired
    private CompanyMapper companyMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private TradeMapper tradeMapper;


    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private DataFunctionMapper dataFunctionMapper;


    @Autowired
    private PaginationService paginationService;

    @RequestMapping( value = "/")
    public String home() {
        return "index";
    }


    @RequestMapping( value = "/home")
    public String index(ModelMap model) {
        int userNum = userMapper.selectUserNum();
        int companyNum = userMapper.selectCetCustNum();
        int cenMemberNum = userMapper.selectCenMemberNum();
        String tradeTotal = tradeMapper.getTradeTotal();
        int allEnquiryNum = projectMapper.getAllEnquiry();
        int allGoodNum = tradeMapper.getAllGoods();
        String priceFlow = tradeMapper.getPriceFlow();
        String selfMall = new BigDecimal(tradeMapper.getSelfMall()).divide(new BigDecimal("10000")).setScale( 2 , BigDecimal.ROUND_HALF_UP).toString();
        model.addAttribute("userNum", userNum);// 注册用户
        model.addAttribute("companyNum", companyNum);// 认证企业
        model.addAttribute("cenMemberNum", cenMemberNum);// 集采供应商
        model.addAttribute("tradeTotal", new BigDecimal(tradeTotal).divide(new BigDecimal("10000")).setScale( 2 , BigDecimal.ROUND_HALF_UP));// 交易总额
        model.addAttribute("allEnquiryNum", allEnquiryNum);// 询价总数
        model.addAttribute("allGoodNum", allGoodNum);// 询价总数
        model.addAttribute("priceFlow", priceFlow);// 交易流水
        model.addAttribute("selfMall", selfMall);// 自营商城
        return "home";
    }

    @RequestMapping( value = "/login" , method = RequestMethod.GET)
    public String login() {
        Admin admin = ContextUtils.getAdmin();
        if(admin != null){
            return "redirect:/";
        }
        return "login";
    }

    @RequestMapping( value = "/loginOut" , method = RequestMethod.GET)
    public String loginOut() {
        ContextUtils.loginOut();
        return "redirect:/login";
    }

    @RequestMapping( value = "/getIndexEnquiry")
    @ResponseBody
    public List<Map<String, Object>> getIndexEnquiry() {
        return tradeMapper.getEnquiryTop5(getParaToInt("limit", 5));
    }

    @RequestMapping( value = "/getIndexOrder")
    @ResponseBody
    public List getIndexOrder() {
//        Page<Object> startPage = PageHelper.startPage(5);
//        List<Map<String, Object>> selectList =  tradeMapper.selectOrderList(null);
//        Pagination paginationList = paginationService.getPaginationList(startPage, selectList);
//        return paginationList.getList();
//
//
        return tradeMapper.getOrderTop5(getParaToInt("limit", 5));
    }


    @RequestMapping( value = "/login"  , method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson logToReport() {
        String name = getPara("user");
        String pwd = getPara("password");
        String verCode = getPara("verCode");
        String sessionVerCode = request.getSession().getAttribute(Globals.VALIDATE_IMAGE).toString();
        if (StrUtil.isBlank(sessionVerCode) || !sessionVerCode.equalsIgnoreCase(verCode)) {
            return AjaxJson.error("验证码有误");
        }
        Admin admin = adminService.validateSubmit(name, pwd);
        if (admin == null) {
            return AjaxJson.error("用户名或密码错误");
        } else {
            Integer roleCount = adminService.selectRoleByAdminId(admin.getId());//根据用户获取权限
            if (roleCount.compareTo(0) == 0) {
                return AjaxJson.error("抱歉，此用户没有权限");
            }
            List<DataFunction> functions = dataFunctionMapper.getFunctionByRoleId(admin.getId());
            if(CollectionUtil.isEmpty(functions)){
                return AjaxJson.error("抱歉，此用户的权限未分配菜单");
            }
            List<DataFunction> firstFuncs = new ArrayList<DataFunction>();
            List<String> uris = new ArrayList<String>();
            for (DataFunction function : functions) {//对菜单进行调整
                if (function.getParentId().compareTo(0) == 0) {//第一层的菜单
                    List<DataFunction> children = new ArrayList<DataFunction>();
                    for (DataFunction dataFunction : functions) {
                        if (dataFunction.getParentId().compareTo(function.getId()) == 0) {
                            children.add(dataFunction);
                            uris.add(dataFunction.getUri());
                        }
                    }
                    function.setChildren(children);
                    firstFuncs.add(function);
                }
            }
            ContextUtils.setFunctions(firstFuncs);//将此用户的菜单放入到session中
            ContextUtils.setUris(uris);//将uri放到session里 方便对权限进行控制
            ContextUtils.setAdmin(admin);
            return AjaxJson.success();
        }
    }


    /**
     * 交易排名top5
     * @return
     */
    @RequestMapping("/getTradePriceTop5")
    @ResponseBody
    public List<Map<String , Object>> getTradePriceTop5() {
        List<Map<String, Object>> list = companyMapper.selectTradePriceTop5();
        return list;
    }





    @RequestMapping("/exportCommon")
    @ResponseBody
    public void exportTradeDetailData(Integer type, String startDate, String endDate, HttpServletRequest request,
                                      HttpServletResponse response) {
        List list = null;
        switch (type) {
            case 1 :{// 每月询报价数量
                list = projectMapper.getProjectsByMonth(startDate, endDate);
                if (list != null) {
                    ExcelExportUtil.exportExcel(
                            new ExportParams("每月询报价数量", null ,  "询报价数量", startDate + "到" + endDate +"询报价数量"),
                            ExcelExportEntityUtil.ProjectsByMonthList(), list,request,response);
                }
                break;
            }
            case 2 :{//新增注册用户、认证转化率及用户增长率情况
                list = userMapper.selectAddUserData(startDate, endDate);
                ExcelExportUtil.exportExcel(new ExportParams("新增注册用户、认证转化率及用户增长率情况", null , "用户增长" , startDate + "到" + endDate +"用户增长转化等情况")
                        , UserAddDto.class, list , request , response);
                break;
            }
            case 3 :{//新增注册企业及增长率
                list = userMapper.selectCompanyData(startDate, endDate);
                ExcelExportUtil.exportExcel(new ExportParams("新增注册企业及增长率", null , "企业增长" , startDate + "到" + endDate +"企业增长概览")
                        , CompanyAddDto.class, list , request , response);
                break;
            }
            case 4 :{//企业各身份增长数量概览
                list = userMapper.selectCerDatas(startDate, endDate);
                ExcelExportUtil.exportExcel(new ExportParams("企业各身份增长数量概览", null , "企业身份" , startDate + "到" + endDate +"企业各身份增长概览")
                        , CompanyStatusDto.class, list , request , response);
                break;
            }
            case 5 :{//浏览量(PV)
                List<Map<String , Object>> pvs = userMapper.selectDayPVNew(startDate, endDate);
                List<PvDataDto> vds = new ArrayList<>();
                for (Map<String , Object> params : pvs) {
                    vds.add(new PvDataDto(params));
                }
                ExcelExportUtil.exportExcel(new ExportParams("热点功能浏览量(PV)", null , "浏览量(PV)" , startDate + "到" + endDate +"热点功能浏览量(PV)")
                        , PvDataDto.class, vds , request , response);
                break;
            }
            case 6 :{//访客量(UV)
                List<Map<String , Object>> uvs = userMapper.selectDayUVNew(startDate, endDate);
                List<PvDataDto> vds = new ArrayList<>();
                for (Map<String, Object> params : uvs) {
                    vds.add(new PvDataDto(params));
                }
                ExcelExportUtil.exportExcel(new ExportParams("热点功能访客量(UV)", null , "访客量(UV)" , startDate + "到" + endDate +"热点功能访客量(UV)")
                        , PvDataDto.class, vds , request , response);
                break;
            }
            case 7 :{//每月被采纳报价数量
                list = projectMapper.getAcceptNums(startDate, endDate);
                if (list != null) {
                    ExcelExportUtil.exportExcel(
                            new ExportParams("每月被采纳报价数量", null ,  "被采纳报价数量", startDate + "到" + endDate +"被采纳报价数量"),
                            ExcelExportEntityUtil.AcceptQuoteList(), list,request,response);
                }
                break;
            }
            case 8 :{//集采供应商报告
                list = projectMapper.selectCenProReport();
                if (list != null) {
                    ExcelExportUtil.exportExcel(new ExportParams("集采供应商数据报告", null , "集采供应商报告" , "集采供应商数据报告")
                            , CentralizeProviderReportDto.class, list , request , response);
                }
                break;
            }
        }
    }
}
